package cn.gdcp.demob;


import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements IOnDataChangeListen{
    private ListView lvStu;
    private Button btnAdd;
    private ArrayList<Student> studentArrayList = new ArrayList<>();
    private StuAdapter adapter;
    private EditText edtKey;
    private ImageView ivSearch;
    private Uri uri = Uri.parse("content://com.gdcp.student/student");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();
        adapter = new StuAdapter(MainActivity.this, studentArrayList,MainActivity.this);
        readDataFromDB();

        lvStu.setAdapter(adapter);
        lvStu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Student student = studentArrayList.get(i);
                Intent intent= new Intent();
                intent.setClass(MainActivity.this,EditActivity.class);
                intent.putExtra("STUDENT",student);
                startActivityForResult(intent,1002);
            }
        });

    }



    //找到控件
    private void findViews() {
        lvStu = findViewById(R.id.lv_stu);
        btnAdd = findViewById(R.id.btn_add);
        edtKey = findViewById(R.id.edt_key);
        ivSearch = findViewById(R.id.iv_search);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, AddActivity.class);
                startActivityForResult(intent, 1001);
            }
        });
        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = edtKey.getText().toString();
                searchFromDB(key);
            }
        });
        edtKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String key = edtKey.getText().toString();
                searchFromDB(key);
            }
        });
    }

    /**
     * 从数据库读取学生列表_1111
     */
    private void readDataFromDB() {
        Cursor cursor= getContentResolver().query(uri,null,null,null,null);
        studentArrayList.clear();
        if(cursor!=null&&cursor.getCount()>0){
            for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
                String stuno=cursor.getString(0);
                String name=cursor.getString(1);
                int age=cursor.getInt(2);
                Student student=new Student(stuno,name,age);
                studentArrayList.add(student);
            }
        }
        cursor.close();
        adapter.notifyDataSetChanged();
    }
    /**
     * 从数据库搜索学生列表_2222
     */
    private void searchFromDB(String key) {
        String where ="name like '%"+key+"%' OR stuno like '%"+key+"%' OR age = '" + key + "'";
        Cursor cursor = getContentResolver().query(uri,null,where,null,null);
        studentArrayList.clear();
        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);
                Student  student = new Student(stuno, name, age);
                studentArrayList.add(student);
            }
        }
        adapter.notifyDataSetChanged();
        cursor.close();
    }

    /*
     * 从数据库删除学生列表_3333
     * */
    @Override
    public void del(Student student) {
        String where ="stuno =+'"+student.getStuno()+"'";
        getContentResolver().delete(uri,where,null);
        readDataFromDB();
    }
    /*
     * 从数据库更新学生列表_4444
     * */
    private void updateFromDB(Student student) {
        String where ="stuno ='"+student.getStuno()+"'";
        ContentValues values=new ContentValues();
        values.put("name",student.getName());
        values.put("age",student.getAge());
        getContentResolver().update(uri,values,where,null);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);//
        if(resultCode == 2001){
            Student s= (Student) data.getSerializableExtra("STUDENT");
            ContentValues values=new ContentValues();
            values.put("stuno",s.getStuno());
            values.put("name",s.getName());
            values.put("age",s.getAge());
            getContentResolver().insert(uri,values);
            readDataFromDB();
        }else if(resultCode == 3001){
            Student student = (Student) data.getSerializableExtra("STUDENT");
            updateFromDB(student);
            readDataFromDB();
        }

    }

}

